import { Typography, Card, Row, Input, Button, message } from "ant-design-vue";

import { defineComponent, reactive } from "vue";
import { useRouter } from "vue-router";
import "./index.less";

import { localOperation, subjectDistribution, filterUnit } from "@/utils";
import config from "@/utils/config";

const { subject, title } = config;

const { Title, Text, Paragraph } = Typography;


const Home = defineComponent({
  setup() {

    const subjectStore = JSON.parse(localOperation.get("subjectList") as any);
    const patchSubjectStore = JSON.parse(localOperation.get("patchSubject") as any);
    const titleStore = localOperation.get("title");
    const $router = useRouter();
    const state: any = reactive({
      defaultData: [],
      isActive: 0,
      gatherError: [],
      gatherTime: [],
      isSuspend: {
        off: false,
        frequency: 0,
        duration: 0,
      },
      fraction: 0,
    });

    state.defaultData = subjectDistribution(patchSubjectStore || subjectStore || subject);
    let times: any, downTime: any;
    /* 提前交卷 */
    const sumitover = () => {
      delete state.isSuspend.off;
      localOperation.set({
        key: "gatherError",
        value: JSON.stringify(state.gatherError),
      });
      localOperation.set({
        key: "isSuspend",
        value: JSON.stringify(state.isSuspend),
      });
      localOperation.set({
        key: "fraction",
        value: JSON.stringify(state.fraction),
      });
      localOperation.set({
        key: "actualTotal",
        value: JSON.stringify(state.isActive),
      });
      clearInterval(times);
      clearInterval(downTime);

      $router.replace({ path: "/result" });
    };
    const submit = (item: any) => () => {
      if (!item.value) {
        message.error('请填写答案再提交！')
        return
      }
      if(isNaN(+item.value)){
        message.error('请输入数字！')
        return
      }
      if (item.type === 5) {
        if (
          +item.value === item.result.merchant &&
          +item.remainder === item.result.remainder
        ) {
          state.fraction += Number(item.fraction);
        } else {
          state.gatherError.push(item);
        }
      } else {
        if (+item.value === item.result) {
          state.fraction += Number(item.fraction);
        } else {
          state.gatherError.push(item);
        }
      }
      /* 无论对错，答题后进入下一题 */
      state.isSuspend.off = false;
      state.isActive = state.isActive + 1;
      clearInterval(times);
      console.log(state.defaultData.length - 1)
      console.log(state.isActive)
      if (state.defaultData.length - 1 < state.isActive) {
        console.log('进入')
        console.log($router)
        sumitover()
      }
    };
    const countDown = (item: any) => {
      times = setInterval(() => {
        item.time--;
        if (item.time <= 0) {
          clearInterval(times)
          state.isActive = state.isActive + 1;
          state.gatherError.push(item);
          if (state.defaultData.length - 1 < state.isActive) {
            console.log('进入')
            console.log($router)
            sumitover()
          }
        }
      }, 1000);
    };



    /* 倒计时恢复与暂停 */
    const timeHandle = (item: any) => () => {
      state.isSuspend.off = !state.isSuspend.off;
      if (state.isSuspend.off) {
        clearInterval(downTime);
        clearInterval(times);
        state.isSuspend.frequency += 1;

        downTime = setInterval(() => {
          state.isSuspend.duration += 1;
        }, 1000);
      } else {
        clearInterval(downTime);
        countDown(item);
      }
    };
    return () => (
      <div class="answers-container">
        <Button onClick={sumitover} type="danger" size="large" style={{ 'position': 'relative', 'right': '-220px', 'marginBottom': '20px' }}>提前交卷</Button>
        <Title>{titleStore || title}</Title>
        {state.defaultData.map((item: any, index: number) => {
          return (
            state.isActive === index && (
              <Card
                style={{ margin: '20px 0' }}
                title={
                  <Text style={{ fontSize: '20px' }}>
                    第{index + 1}题/共{state.defaultData.length}题
                  </Text>
                }
              >
                <Row justify="start" align="middle" style={{ marginBottom: '20px' }}>
                  <Text style={{ fontSize: '30px' }}>
                    {item.L}
                    {filterUnit(item.type)}
                    {item.R}=
                  </Text>
                  <Input style={{ fontSize: '30px' }}  v-model={[item.value, "value"]} onPressEnter={submit(item)} />

                  {item.type === 5 && (
                    <>
                      ... <Input  style={{ fontSize: '30px' }}  v-model={[item.remainder, "value"]} onPressEnter={submit(item)} />
                    </>
                  )}

                  <Button onClick={submit(item)}>提交</Button>
                </Row>
                <Row justify="start" align="middle">
                  {countDown(item)}
                  <Text style={{ fontSize: '26px' }} >倒计时：{item.time}</Text>
                  <Button onClick={timeHandle(item)}>
                    {!state.isSuspend.off ? "暂停" : "恢复"}
                  </Button>
                </Row>
              </Card>
            )
          );
        })}
      </div>
    );
  },
});
export default Home;
